package com.zzyl.framework.interceptor;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.common.utils.UserThreadLocal;
import lombok.SneakyThrows;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Autowired
    private HttpServletRequest request;

    @SneakyThrows
    public boolean isExclude() {
        try {
            String requestURI = request.getRequestURI();
            if(requestURI.startsWith("/member")){
                return true;
            }
            return false;
        } catch (Exception e) {
            return true;
        }
    }
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        // 自动填充创建人
        if(isExclude()) {
            this.strictInsertFill(metaObject, "createBy", String.class, getLoginUser() + "");
        }else {
            this.setFieldValByName("updateBy", getLoginUser(), metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", new Date(), metaObject);
        if(isExclude()) {
            this.setFieldValByName("updateBy", getLoginUser() + "", metaObject);
        }else {
            this.setFieldValByName("updateBy", getLoginUser(), metaObject);
        }
    }

    // 获取当前用户
    public Long getLoginUser() {
        try {
        return UserThreadLocal.getUserId();
        }catch (Exception e){
            // 未登录（定时任务或者数据上报）
            return 1L;
        }
    }
}